<template>
  <view class="tomato-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">番茄钟</text>
    </view>
    
    <!-- 计时器圆环 -->
    <view class="timer-section">
      <view class="timer-container">
        <!-- 背景圆环 -->
        <canvas canvas-id="progressRing" class="progress-ring"></canvas>
        
        <!-- 计时器显示 -->
        <view class="timer-content">
          <text class="timer-text">{{ formatTime }}</text>
          <text class="phase-text">{{ isFocus ? '专注时间' : '休息时间' }}</text>
        </view>
      </view>
      
      <!-- 状态提示 -->
      <view class="status-indicator">
        <text class="status-text">{{ statusText }}</text>
      </view>
    </view>
    
    <!-- 控制按钮 -->
    <view class="control-buttons">
      <button 
        class="control-btn secondary" 
        @click="resetTimer"
        :disabled="timeLeft === (isFocus ? 25 * 60 : 5 * 60) && !isRunning"
      >
        重置
      </button>
      <button 
        class="control-btn primary" 
        @click="toggleTimer"
      >
        {{ isRunning ? '暂停' : '开始' }}
      </button>
      <button 
        class="control-btn secondary" 
        @click="togglePhase"
        :disabled="isRunning"
      >
        切换阶段
      </button>
    </view>
    
    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-label">今日完成</text>
        <text class="stat-value">{{ todayCompleted }}个</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item">
        <text class="stat-label">总时长</text>
        <text class="stat-value">{{ totalTime }}分钟</text>
      </view>
    </view>
  </view>
</template>

<script>
// 导入本地存储工具
import { getStorage, setStorage } from '../../utils/storage.js'

export default {
  data() {
    return {
      timeLeft: 25 * 60, // 初始25分钟
      isRunning: false,
      timer: null,
      isFocus: true, // 是否是专注阶段
      focusDuration: 25 * 60, // 专注时长（秒）
      breakDuration: 5 * 60, // 休息时长（秒）
      todayCompleted: 0, // 今日完成的番茄数
      totalTime: 0, // 今日总时长（分钟）
      progressWidth: 8 // 进度环宽度
    }
  },
  computed: {
    formatTime() {
      const min = Math.floor(this.timeLeft / 60)
      const sec = this.timeLeft % 60
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
    },
    statusText() {
      if (this.isRunning) {
        return this.isFocus ? '专注中，加油！' : '休息时间，放松一下'
      } else {
        return this.isFocus ? '准备开始专注' : '准备开始休息'
      }
    },
    // 计算进度百分比
    progressPercent() {
      const totalDuration = this.isFocus ? this.focusDuration : this.breakDuration
      return 1 - (this.timeLeft / totalDuration)
    }
  },
  onLoad() {
    // 初始化数据
    this.initData()
    // 绘制初始进度环
    this.drawProgressRing()
  },
  onUnload() {
    clearInterval(this.timer)
  },
  methods: {
    // 初始化数据
    initData() {
      // 从本地存储获取今日完成数和总时长
      const today = new Date().toLocaleDateString()
      const tomatoData = getStorage('TOMATO_DATA') || {}
      
      if (tomatoData[today]) {
        this.todayCompleted = tomatoData[today].completed || 0
        this.totalTime = tomatoData[today].totalTime || 0
      } else {
        tomatoData[today] = { completed: 0, totalTime: 0 }
        setStorage('TOMATO_DATA', tomatoData)
      }
    },
    
    // 绘制进度环
    drawProgressRing() {
      const ctx = uni.createCanvasContext('progressRing', this)
      const radius = 100 // 圆环半径
      const centerX = 120 // 圆心x坐标
      const centerY = 120 // 圆心y坐标
      
      // 清除画布
      ctx.clearRect(0, 0, 240, 240)
      
      // 绘制背景圆环
      ctx.beginPath()
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
      ctx.setLineWidth(this.progressWidth)
      ctx.setStrokeStyle('rgba(255, 255, 255, 0.3)')
      ctx.stroke()
      
      // 绘制进度圆环
      const startAngle = -Math.PI / 2 // 起始角度（12点方向）
      const endAngle = startAngle + 2 * Math.PI * this.progressPercent
      
      ctx.beginPath()
      ctx.arc(centerX, centerY, radius, startAngle, endAngle)
      ctx.setLineWidth(this.progressWidth)
      ctx.setStrokeStyle(this.isFocus ? '#42b983' : '#f5576c')
      ctx.setLineCap('round')
      ctx.stroke()
      
      ctx.draw()
    },
    
    // 更新数据到本地存储
    updateTomatoData() {
      const today = new Date().toLocaleDateString()
      const tomatoData = getStorage('TOMATO_DATA') || {}
      
      if (!tomatoData[today]) {
        tomatoData[today] = { completed: 0, totalTime: 0 }
      }
      
      tomatoData[today].completed = this.todayCompleted
      tomatoData[today].totalTime = this.totalTime
      
      setStorage('TOMATO_DATA', tomatoData)
    },
    
    // 切换计时器状态
    toggleTimer() {
      if (this.isRunning) {
        // 暂停
        clearInterval(this.timer)
      } else {
        // 开始
        this.timer = setInterval(() => {
          this.timeLeft--
          this.drawProgressRing()
          
          if (this.timeLeft <= 0) {
            this.finishPhase()
          }
        }, 1000)
      }
      this.isRunning = !this.isRunning
    },
    
    // 完成一个阶段
    finishPhase() {
      clearInterval(this.timer)
      this.isRunning = false
      
      // 如果是专注阶段完成，增加番茄数
      if (this.isFocus) {
        this.todayCompleted++
        this.totalTime += 25
        this.updateTomatoData()
        
        // 显示完成提示
        uni.showToast({
          title: '专注完成！',
          icon: 'success',
          duration: 1500
        })
      }
      
      // 切换阶段
      this.isFocus = !this.isFocus
      this.timeLeft = this.isFocus ? this.focusDuration : this.breakDuration
      
      // 重置进度环
      this.drawProgressRing()
    },
    
    // 重置计时器
    resetTimer() {
      clearInterval(this.timer)
      this.isRunning = false
      this.timeLeft = this.isFocus ? this.focusDuration : this.breakDuration
      this.drawProgressRing()
    },
    
    // 切换阶段
    togglePhase() {
      clearInterval(this.timer)
      this.isRunning = false
      this.isFocus = !this.isFocus
      this.timeLeft = this.isFocus ? this.focusDuration : this.breakDuration
      this.drawProgressRing()
    }
  }
}
</script>

<style scoped>

.tomato-page {
  padding: 20rpx;
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
}

/* 页面标题 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

/* 计时器部分 */
.timer-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.timer-container {
  position: relative;
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 30rpx;
}

.progress-ring {
  width: 240rpx;
  height: 240rpx;
  transform: rotate(-90deg);
}

.timer-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.timer-text {
  font-size: 72rpx;
  font-weight: bold;
  color: white;
  text-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
}

.phase-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 10rpx;
  display: block;
}

/* 状态提示 */
.status-indicator {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 25rpx;
  padding: 15rpx 30rpx;
  backdrop-filter: blur(10rpx);
}

.status-text {
  font-size: 26rpx;
  color: white;
  font-weight: 500;
}

/* 控制按钮 */
.control-buttons {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  margin-bottom: 60rpx;
  flex-wrap: wrap;
}

.control-btn {
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: none;
  outline: none;
  transition: all 0.3s ease;
  min-width: 120rpx;
}

.control-btn:active {
  transform: scale(0.95);
}

.control-btn.primary {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  box-shadow: 0 6rpx 20rpx rgba(33, 150, 243, 0.4);
}

.control-btn.secondary {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
}

.control-btn:disabled {
  opacity: 0.5;
}

/* 统计信息 */
.stats-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stat-divider {
  width: 2rpx;
  height: 60rpx;
  background: #eee;
}
</style>